package com.coolsummer.headler;

import com.coolsummer.abstracts.Limiter;
import com.coolsummer.annotions.LimiterAnnotion;
import com.coolsummer.enums.LimiterEnum;
import com.coolsummer.limiter.LimiterFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author coolsummer
 * @describe 限流拦截器
 * @date 2019/11/22 10:55
 */
@Slf4j
public class LimiterHandler implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            LimiterAnnotion methodAnnotation = handlerMethod.getMethodAnnotation(LimiterAnnotion.class);
            if(methodAnnotation != null){
                Limiter limiter = LimiterFactory.create(LimiterEnum.GUAVA_LIMITER, 100);
                if(limiter == null){
                    throw new NullPointerException("redisLimit is null");
                }
                boolean limit = limiter.tryAcquire();
                if (!limit) {
                    log.debug("request has bean limit");
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
